package test.top2.com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import test.top2.com.atguigu.app.fun.DimAsyncFunction;
import test.top2.com.atguigu.bean.TradeSkuOrderBean;
import test.top2.com.atguigu.utils.MyClickHouseUtil;
import test.top2.com.atguigu.utils.MyKafkaUtil;
import test.top2.com.atguigu.utils.WindowFunctionUtil;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: Dws09_TradeSkuOrderWindow
 * Package: test.top2.com.atguigu.app.dws
 * Description:
 *
 * @Author ChenJun(有志男青年)
 * @Create 2023/5/11 15:25
 * @Version 1.0
 */
public class Dws09_TradeSkuOrderWindow {
    public static void main(String[] args) throws Exception {

        //TODO 1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(60 * 1000L);
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
//        env.getCheckpointConfig().enableExternalizedCheckpoints(
//                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION
//        );
//        env.setRestartStrategy(RestartStrategies.failureRateRestart(
//                10, Time.of(1L, TimeUnit.DAYS), Time.of(3L, TimeUnit.MINUTES)
//        ));
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
//        System.setProperty("HADOOP_USER_NAME", "atguigu");

        //TODO 2.读取Kafka DWD层下单明细主题数据
        DataStreamSource<String> kafkaDS = env.fromSource(MyKafkaUtil.getKafkaSource("dwd_trade_order_detail", "sku_order_221109"), WatermarkStrategy.noWatermarks(), "kafka-source");

        //TODO 3.过滤&转换为JSON对象
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.flatMap(new RichFlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                if (value != null) {
                    out.collect(JSON.parseObject(value));
                }
            }
        });

        //TODO 4.提取时间戳生成Watermark
        SingleOutputStreamOperator<JSONObject> jsonObjWithWMDS = jsonObjDS.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject element, long recordTimestamp) {
                return element.getLong("create_time");
            }
        }));

        //TODO 5.按照订单明细ID分组
        KeyedStream<JSONObject, String> keyedByDetailIdDS = jsonObjWithWMDS.keyBy(json -> json.getString("id"));

        //TODO 6.去重,并转换为JavaBean对象
        SingleOutputStreamOperator<TradeSkuOrderBean> tradeSkuOrderDS = keyedByDetailIdDS.flatMap(new RichFlatMapFunction<JSONObject, TradeSkuOrderBean>() {

            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {

                StateTtlConfig ttlConfig = new StateTtlConfig.Builder(Time.seconds(5))
                        .setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite)
                        .build();

                ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("value-state", String.class);
                stateDescriptor.enableTimeToLive(ttlConfig);

                valueState = getRuntimeContext().getState(stateDescriptor);

            }

            @Override
            public void flatMap(JSONObject value, Collector<TradeSkuOrderBean> out) throws Exception {

                //取出状态数据
                String state = valueState.value();

                if (state == null) {
                    valueState.update("1");

                    BigDecimal splitActivityAmount = value.getBigDecimal("split_activity_amount");

                    out.collect(TradeSkuOrderBean.builder()
                            .skuId(value.getString("sku_id"))
                            .skuName(value.getString("sku_name"))
                            .originalAmount(value.getBigDecimal("split_original_amount"))
                            .orderAmount(value.getBigDecimal("split_total_amount"))
                            .activityAmount(splitActivityAmount == null ? new BigDecimal("0.0") : splitActivityAmount)
                            .couponAmount(value.getBigDecimal("split_coupon_amount"))
                            .build());
                }
            }
        });

        //TODO 7.按照SKU分组、开窗、聚合
        SingleOutputStreamOperator<TradeSkuOrderBean> reduceDS = tradeSkuOrderDS.keyBy(TradeSkuOrderBean::getSkuId).window(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10))).reduce(new ReduceFunction<TradeSkuOrderBean>() {
            @Override
            public TradeSkuOrderBean reduce(TradeSkuOrderBean value1, TradeSkuOrderBean value2) throws Exception {
                value1.setOriginalAmount(value1.getOriginalAmount().add(value2.getOriginalAmount()));
                value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));
                value1.setActivityAmount(value1.getActivityAmount().add(value2.getActivityAmount()));
                value1.setCouponAmount(value1.getCouponAmount().add(value2.getCouponAmount()));
                return value1;
            }
        }, new WindowFunction<TradeSkuOrderBean, TradeSkuOrderBean, String, TimeWindow>() {
            @Override
            public void apply(String s, TimeWindow window, Iterable<TradeSkuOrderBean> input, Collector<TradeSkuOrderBean> out) throws Exception {
                //                        TradeSkuOrderBean next = input.iterator().next();
//                        next.setTs(System.currentTimeMillis());
//                        next.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
//                        next.setStt(DateFormatUtil.toYmdHms(window.getStart()));
//                        out.collect(next);

                WindowFunctionUtil.set(input, window, out);
            }
        });
        reduceDS.print("reduceDS-->");

        //TODO 8.关联维表,补充维度信息

        //TODO 8.1 关联SKU  dim_sku_info
        SingleOutputStreamOperator<TradeSkuOrderBean> dimSkuInfoDS = AsyncDataStream.unorderedWait(reduceDS, new DimAsyncFunction<TradeSkuOrderBean>("DIM_SKU_INFO") {
            @Override
            public String getKey(TradeSkuOrderBean input) {
                return input.getSkuId();
            }

            @Override
            public void join(TradeSkuOrderBean input, JSONObject dimInfo) {
                input.setSpuId(dimInfo.getString("SPU_ID"));
                input.setTrademarkId(dimInfo.getString("TM_ID"));
                input.setCategory3Id(dimInfo.getString("CATEGORY3_ID"));
            }
        }, 60, TimeUnit.SECONDS);

        dimSkuInfoDS.print("dimSkuInfoDS-->");

        //TODO 8.2 关联SPU  dim_spu_info
        SingleOutputStreamOperator<TradeSkuOrderBean> dimSpuInfoDS = AsyncDataStream.unorderedWait(dimSkuInfoDS,
                new DimAsyncFunction<TradeSkuOrderBean>("DIM_SPU_INFO") {
                    @Override
                    public String getKey(TradeSkuOrderBean input) {
                        return input.getSpuId();
                    }

                    @Override
                    public void join(TradeSkuOrderBean input, JSONObject dimInfo) {
                        input.setSpuName(dimInfo.getString("SPU_NAME"));
                    }
                }, 60, TimeUnit.SECONDS);

        //TODO 8.3 关联Trademark  dim_base_trademark
        SingleOutputStreamOperator<TradeSkuOrderBean> dimTrademarkInfoDS = AsyncDataStream.unorderedWait(dimSpuInfoDS,
                new DimAsyncFunction<TradeSkuOrderBean>("DIM_BASE_TRADEMARK") {
                    @Override
                    public String getKey(TradeSkuOrderBean input) {
                        return input.getTrademarkId();
                    }

                    @Override
                    public void join(TradeSkuOrderBean input, JSONObject dimInfo) {
                        input.setTrademarkName(dimInfo.getString("TM_NAME"));
                    }
                }, 60, TimeUnit.SECONDS);

        //TODO 8.4 关联Category3  dim_base_category3
        SingleOutputStreamOperator<TradeSkuOrderBean> dimCategory3InfoDS = AsyncDataStream.unorderedWait(dimTrademarkInfoDS,
                new DimAsyncFunction<TradeSkuOrderBean>("DIM_BASE_CATEGORY3") {
                    @Override
                    public String getKey(TradeSkuOrderBean input) {
                        return input.getCategory3Id();
                    }

                    @Override
                    public void join(TradeSkuOrderBean input, JSONObject dimInfo) {
                        input.setCategory3Name(dimInfo.getString("NAME"));
                        input.setCategory2Id(dimInfo.getString("CATEGORY2_ID"));

                    }
                }, 60, TimeUnit.SECONDS);

        //TODO 8.5 关联Category2  dim_base_category2
        SingleOutputStreamOperator<TradeSkuOrderBean> dimCategory2InfoDS =
                AsyncDataStream.unorderedWait(dimCategory3InfoDS,
                new DimAsyncFunction<TradeSkuOrderBean>("DIM_BASE_CATEGORY2") {
                    @Override
                    public String getKey(TradeSkuOrderBean input) {
                        return input.getCategory2Id();
                    }

                    @Override
                    public void join(TradeSkuOrderBean input, JSONObject dimInfo) {
                        input.setCategory2Name(dimInfo.getString("NAME"));
                        input.setCategory1Id(dimInfo.getString("CATEGORY1_ID"));
                    }
                }, 60, TimeUnit.SECONDS);

        //TODO 8.6 关联Category1  dim_base_category1
        SingleOutputStreamOperator<TradeSkuOrderBean> dimCategory1InfoDS =
                AsyncDataStream.unorderedWait(dimCategory2InfoDS,
                        new DimAsyncFunction<TradeSkuOrderBean>("DIM_BASE_CATEGORY1") {
                            @Override
                            public String getKey(TradeSkuOrderBean input) {
                                return input.getCategory1Id();
                            }

                            @Override
                            public void join(TradeSkuOrderBean input, JSONObject dimInfo) {
                                input.setCategory1Name(dimInfo.getString("NAME"));
                            }
                        }, 60, TimeUnit.SECONDS);

        dimCategory1InfoDS.print("dimCategory1InfoDS-->");

        //TODO 9.写出数据
        dimCategory1InfoDS.addSink(MyClickHouseUtil.getSinkFunction("insert into dws_trade_sku_order_window values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"));

        //TODO 10.启动任务
        env.execute("Dws09_TradeSkuOrderWindow");
    }
}
